<!-- @format -->

<script setup lang="ts">
import TheIcon from '@/components/TheIcon.vue'
import { computed, ref } from 'vue'

import { useHelper } from '../../composables/useHelper'
import { useNavHome } from '../../composables/useNavHome'
import { useShare } from '../../composables/useShare'

import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import theColors from './components/theColors.vue'

import { debounce } from '@/utils/commonUtils'
import { md5 } from '@/utils/md5Utils'
import axios from 'axios-miniprogram'
import { useToast } from 'wot-design-uni'
import { useUserService } from '../../composables/useUserService.ts'
import { BG_COLORS_BG } from './components/conf.ts'
import confNodeTextPopup from './components/confNodeTextPopup.vue'
import confStyleAnswers from './components/confStyleAnswers.vue'

const toast = useToast()
const loading = ref(true)
const shareTitle = ref('')
const isDirty = ref(false)
const options = ref({})

// 生成一个随机数 当前时间+随机数 md5转换一下
const random = Math.floor(Math.random() * 100000)
const timestamp = new Date().getTime()
const randomNum = timestamp + random
const shareDataId = md5(randomNum.toString())

const { openId, updateData } = useShare(shareDataId)
const { updateUserConf } = useUserService()

const loadShareData = async () => {
  shareTitle.value = options.value?.title || ''
  if (options.value?.id) {
    let id = options.value?.id
    let oid = options.value?.oid
    const { content, getData } = useShare(id, { share: true, oid })
    await getData()

    if (content.value) {
      if (content.value.nodes) {
        nodes.value = content.value.nodes
        // 取得最后一个节点的id
        const lastNode = nodes.value[nodes.value.length - 1]
        if (lastNode) {
          id = lastNode.id
        }
      }
      // 应用背景
      const bgData = content.value.bgData
      if (bgData?.color) {
        bgColor.value = bgData.color
      }
      if (bgData?.purl) {
        fileList.value = [{ url: bgData.purl }]
      } else if (bgData?.url) {
        fileList.value = [{ url: bgData.url }]
      }
      // 应用答案
      if (content.value.answers) {
        answers.value = content.value.answers
      }
    }
  }
  loading.value = false
}
onLoad((option) => {
  options.value = option
  loadShareData()
})

onShareAppMessage(() => {
  let id = options.value?.id
  let oid = options.value?.oid
  if (!id || isDirty.value) {
    id = shareDataId
    oid = openId.value
  }
  return {
    title: shareTitle.value || '爱分享',
    path: `/pages/minishare/shareNext?id=${id}&oid=${oid}&title=${shareTitle.value}`,
  }
})

let id = 1

const showConfText = ref(false)
const tab = ref(0)

const defaultTextNode = {
  title: '请输入内容',
  type: 'text',
  content: '点击文本选中',
  x: 180,
  y: 240,
}

const nodes = ref([
  {
    id: 1,
    ...defaultTextNode,
  },
])
const selectNode = ref(nodes.value[0])

const fileList = ref<any>([])
const bgColor = ref(BG_COLORS_BG[0])
const bgData = computed(() => {
  const file = fileList.value[0]
  if (file) {
    let url = file.url
    let purl = file.purl

    return { url, purl }
  }
  return {
    color: bgColor.value,
  }
})

const answers = ref({
  title: '答案：',
  content: '',
})

const dataChange = debounce(() => {
  isDirty.value = true

  updateData({
    nodes: nodes.value,
    bgData: bgData.value,
    answers: answers.value,
  })
})

const changeBgColor = (color) => {
  bgColor.value = color
  dataChange()
}

// const host = ref<string>(
//   'https://api.cloudinary.com/v1_1/dbwkyvqao/image/upload'
// )
// const buildFormData = ({ file, formData, resolve }) => {
//   let imageName = file.url.substring(file.url.lastIndexOf('/') + 1) // 从图片路径中截取图片名称
//   const key = `${imageName}` // 图片上传到oss的路径(拼接你的文件夹和文件名)

//   formData = {
//     ...formData,
//     key,
//     upload_preset: 'ariticle-shares', // 无签名预设
//     api_key: '116345838119862', // 客户端需暴露 api_key（已通过域名限制安全）
//     success_action_status: '200',
//   }
//   resolve(formData) // 组装成功后返回 formData，必须返回
// }
const host = ref<string>('https://md-article.oss-cn-beijing.aliyuncs.com')

const ossUploadData = ref<any>(null)

const getOssUploadData = async () => {
  if (ossUploadData.value) return
  const { data } = await axios.get(
    'https://m-scrm-cn-test.geely-test.com/api/demo/sign'
  )
  ossUploadData.value = data
  return ossUploadData.value
}

const buildFormData = ({ file, formData, resolve }) => {
  getOssUploadData().then((res) => {
    let imageName = file.url.substring(file.url.lastIndexOf('/') + 1) // 从图片路径中截取图片名称
    const { policy, signature, accessKeyId, dir } = res
    const key = `${dir}${imageName}` // 图片上传到oss的路径(拼接你的文件夹和文件名)
    const success_action_status = '200' // 将上传成功状态码设置为200，默认状态码为204

    formData = {
      ...formData,
      key: key,
      OSSAccessKeyId: accessKeyId,
      policy: policy,
      signature: signature,
      success_action_status: success_action_status,
    }
    resolve(formData) // 组装成功后返回 formData，必须返回
  })
}

const handleRemove = () => {
  fileList.value = []
  dataChange()
}

const handleChange = (res) => {
  const file = res.fileList[0]
  let imageName = file.url.substring(file.url.lastIndexOf('/') + 1) // 从图片路径中截取图片名称
  const { dir } = ossUploadData.value
  const key = `${dir}${imageName}` // 图片上传到oss的路径(拼接你的文件夹和文件名)

  file.purl = `${host.value}/${key}`
  fileList.value = [file]

  dataChange()
}

const handleFail = (res) => {
  fileList.value = [res.file]
  dataChange()
}

const handleUpload = (file, formData, options) => {
  options.onSuccess({}, file, formData)
  options.onProgress({ progress: 100 }, file)
}

const onNodesChange = (node) => {
  const list = nodes.value
  const index = list.findIndex((item) => item.id === node.id)
  list[index] = node
  nodes.value = list
  selectNode.value = node
  dataChange()
}

const toSelect = (node) => {
  selectNode.value = node
  showConfText.value = true
}

const toRemove = (node) => {
  const list = nodes.value
  nodes.value = list.filter((item) => item.id !== node.id)
  selectNode.value = null
  dataChange()
}

let prevLocal = { x: 0, y: 0 }
const getNextLocal = () => {
  const next = { ...prevLocal }
  next.x += 20
  next.y += 20

  if (next.x > 600) {
    next.x = 0
  }
  if (next.y > 500) {
    next.y = 0
  }
  prevLocal = { ...next }
  return next
}

const addNode = () => {
  let lastNode = {}
  let length = nodes.value.length

  for (let i = length - 1; i > -1; i--) {
    const node = nodes.value[i]

    if (node.type === 'text') {
      lastNode = node
      break
    }
  }
  id++
  const node = { ...defaultTextNode, ...lastNode, ...getNextLocal(), id }
  nodes.value.push(node)
  toSelect(node)
  dataChange()
}

const onBacktop = async () => {
  await updateUserConf({ homePath: '/pages/minishare/minishare' })
  toast.show('设置成功')
}

const { handleBack, handleBackHome } = useNavHome()
const { randomMsg } = useHelper()
</script>

<template>
  <view>
    <wd-navbar fixed placeholder safeAreaInsetTop>
      <template #left>
        <view class="nav-left">
          <the-capsule></the-capsule>
          <!-- <wd-navbar-capsule @back="handleBack" @back-home="handleBackHome" /> -->
          <the-icon class="the-add-btn" icon="add" @click="addNode">
            文本
          </the-icon>
        </view>
      </template>
    </wd-navbar>
    <share-view
      :loading="loading"
      :bgData="bgData"
      :nodes="nodes"
      @select="toSelect"
      @change="onNodesChange"
    ></share-view>
    <view class="tools-x" :class="{ active: !loading }">
      <wd-tabs v-model="tab" animated>
        <wd-tab title="背景">
          <div class="block">
            <div>
              <div class="title-tip">背景图:</div>
              <!-- :upload-method="handleUpload" -->
              <wd-upload
                :file-list="fileList"
                limit="1"
                :show-limit-num="false"
                :action="host"
                :build-form-data="buildFormData"
                @remove="handleRemove"
                @change="handleChange"
                @fail="handleFail"
              ></wd-upload>
              <div class="info-tip">图片最大限制：2M</div>
            </div>

            <div v-if="!fileList?.length">
              <div class="title-tip">背景色:</div>
              <the-colors
                :colors="BG_COLORS_BG"
                :current="bgColor || BG_COLORS_BG[0]"
                @change="changeBgColor"
              ></the-colors>
            </div>
          </div>
        </wd-tab>

        <wd-tab title="内容">
          <confStyleAnswers
            @change="dataChange"
            :styl-data="answers"
          ></confStyleAnswers>
        </wd-tab>

        <wd-tab title="分享标题">
          <div class="block">
            <wd-input
              type="text"
              v-model="shareTitle"
              placeholder="请输入分享标题"
            />
          </div>
        </wd-tab>
      </wd-tabs>

      <div class="func">
        <div class="helper-tip">{{ randomMsg }}</div>
        <wd-button
          open-type="share"
          icon="share"
          custom-style="flex:1; margin-right: 16rpx; background-color: #1bb56a;"
          >分享</wd-button
        >
        <wd-button icon="add" plain size="small" hairline @click="addNode"
          >文本</wd-button
        >
      </div>
    </view>
    <wd-toast />
    <confNodeTextPopup
      :conf="selectNode"
      @change="onNodesChange"
      @remove="toRemove"
      v-model:show="showConfText"
    ></confNodeTextPopup>
  </view>
</template>
<style lang="scss" scoped>
.nav-left {
  display: flex;
  align-items: center;
}
.tools-x {
  opacity: 0;
  transition: opacity 0.3s;
}
.tools-x.active {
  opacity: 1;
}

.the-add-btn {
  margin-left: 16rpx;
  line-height: 1;
  padding: 16rpx;

  font-size: 28rpx;
  border-radius: 40rpx;
  background-color: #1bb56a;
  color: white;
}
.c-blue {
  background-color: blue;
}
.block {
  padding: 20rpx;
  min-height: 60vw;

  ::v-deep {
    .wd-upload {
      justify-content: center;
    }

    .wd-upload__evoke,
    .wd-upload__preview {
      width: 25vw;
      height: 20vw;
    }
  }
}
.func {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16rpx 20rpx;
  padding-bottom: 80rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}
.block-cell {
  display: flex;
  align-items: center;
}
.title-tip {
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
  padding-right: 20rpx;
}
.info-tip {
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
.helper-tip {
  position: absolute;
  left: 0;
  right: 0;
  top: -50rpx;
  text-align: center;
  color: #999;
  font-size: 24rpx;
}
</style>
